package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.domain.RecKjInsideManagement;
import com.ruoyi.system.domain.RecZmPaperInsideManagement;
import com.ruoyi.system.mapper.RecKjInsideManagementMapper;
import com.ruoyi.system.service.IRecKjInsideManagementService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.validation.Validator;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * 会计档案 案卷管理Service业务层处理
 *
 * @author yzf
 * @date 2022-06-03
 */
@Service
public class RecKjInsideManagementServiceImpl implements IRecKjInsideManagementService {
    @Autowired
    protected Validator validator;
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RecKjInsideManagementMapper recKjInsideManagementMapper;

    /**
     * 查询会计档案 案卷管理
     *
     * @param id 会计档案 案卷管理主键
     * @return 会计档案 案卷管理
     */
    @Override
    public RecKjInsideManagement selectRecKjInsideManagementById(String id) {
        return recKjInsideManagementMapper.selectRecKjInsideManagementById(id);
    }

    /**
     * 查询会计档案 案卷管理列表
     *
     * @param recKjInsideManagement 会计档案 案卷管理
     * @return 会计档案 案卷管理
     */
    @Override
    public List<RecKjInsideManagement> selectRecKjInsideManagementList(RecKjInsideManagement recKjInsideManagement) {
        return recKjInsideManagementMapper.selectRecKjInsideManagementList(recKjInsideManagement);
    }

    public List<RecKjInsideManagement> recKjInsideManagementListByParentId(String parentId) {
        RecKjInsideManagement rk = new RecKjInsideManagement();
        rk.setParentId(parentId);
        return recKjInsideManagementMapper.selectRecKjInsideManagementList(rk);
    }

    @Override
    public List<Map<String, Object>> selectlistByName(RecKjInsideManagement recKjInsideManagement) {
        return recKjInsideManagementMapper.selectlistByName(recKjInsideManagement);
    }

    /**
     * 新增会计档案 案卷管理
     *
     * @param recKjInsideManagement 会计档案 案卷管理
     * @return 结果
     */
    @Override
    public int insertRecKjInsideManagement(RecKjInsideManagement recKjInsideManagement) {
        recKjInsideManagement.setCreateTime(DateUtils.getNowDate());
        recKjInsideManagement.setCreateBy(SecurityUtils.getUsername());
        return recKjInsideManagementMapper.insertRecKjInsideManagement(recKjInsideManagement);
    }

    /**
     * 修改会计档案 案卷管理
     *
     * @param recKjInsideManagement 会计档案 案卷管理
     * @return 结果
     */
    @Override
    public int updateRecKjInsideManagement(RecKjInsideManagement recKjInsideManagement) {
        recKjInsideManagement.setUpdateTime(DateUtils.getNowDate());
        recKjInsideManagement.setUpdateBy(SecurityUtils.getUsername());
        return recKjInsideManagementMapper.updateRecKjInsideManagement(recKjInsideManagement);
    }

    /**
     * 批量删除会计档案 案卷管理
     *
     * @param ids 需要删除的会计档案 案卷管理主键
     * @return 结果
     */
    @Override
    public int deleteRecKjInsideManagementByIds(String[] ids) {
        return recKjInsideManagementMapper.deleteRecKjInsideManagementByIds(ids);
    }

    /**
     * 删除会计档案 案卷管理信息
     *
     * @param id 会计档案 案卷管理主键
     * @return 结果
     */
    @Override
    public int deleteRecKjInsideManagementById(String id) {
        return recKjInsideManagementMapper.deleteRecKjInsideManagementById(id);
    }

    @Override
    @Transactional
    public int updateArchivesApplyByIds(String[] Ids) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (String id : Ids) {
            RecKjInsideManagement recordArchives = new RecKjInsideManagement();
            recordArchives.setId(id);
            recordArchives.setObjStr1("1"); //申请状态字段，1：申请
            RecKjInsideManagement recordArchivesOld = this.selectRecKjInsideManagementById(id);
            if ("0".equals(recordArchivesOld.getObjStr1()) || "3".equals(recordArchivesOld.getObjStr1())) { // 未申请或拒绝状态，可申请
                int res = this.updateRecKjInsideManagement(recordArchives);
                if (res != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作未申请和审批拒绝的案卷");
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int updateArchivesApprove(String[] ids) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (String id : ids) {
            RecKjInsideManagement recordArchives = new RecKjInsideManagement();
            recordArchives.setId(id);
            recordArchives.setObjStr1("2"); //申请状态字段,2：通过
            RecKjInsideManagement recordArchivesOld = recKjInsideManagementMapper.selectRecKjInsideManagementById(id);
            // 如果总登记号为0，自增+1
//            if(recordArchivesOld.getRegistNum() == 0){
//                List<RecordArchives> archList = recordArchivesMapper.selectRegistNumCount();
//                if(archList.size() != 0){
//                    recordArchives.setRegistNum(archList.get(0).getRegistNum() + 1);
//                }else {
//                    recordArchives.setRegistNum(1); // 第一次添加
//                }
//            }
            if ("1".equals(recordArchivesOld.getObjStr1())) { // 申请中状态，可审批
                int res = this.updateRecKjInsideManagement(recordArchives);
                if (res != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作申请中的案卷");
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int updateArchivesReject(String[] ids) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (String id : ids) {
            RecKjInsideManagement recordArchives = new RecKjInsideManagement();
            recordArchives.setId(id);
            recordArchives.setObjStr1("3"); //申请状态字段，3：拒绝
            RecKjInsideManagement recordArchivesOld = recKjInsideManagementMapper.selectRecKjInsideManagementById(id);
            // 如果总登记号为0，自增+1
//            if(recordArchivesOld.getRegistNum() == 0){
//                List<RecordArchives> archList = recordArchivesMapper.selectRegistNumCount();
//                if(archList.size() != 0){
//                    recordArchives.setRegistNum(archList.get(0).getRegistNum() + 1);
//                }else {
//                    recordArchives.setRegistNum(1); // 第一次添加
//                }
//            }
            if ("1".equals(recordArchivesOld.getObjStr1())) { // 申请中状态，可审批
                int res = this.updateRecKjInsideManagement(recordArchives);
                if (res != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作申请中的案卷");
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public String importFile(List<RecKjInsideManagement> fileList, String operName) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        if (StringUtils.isNull(fileList) || fileList.size() == 0) {
            throw new ServiceException("导入文件数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (RecKjInsideManagement file : fileList) {
            try {
                BeanValidators.validateWithException(validator, file);
                file.setCreateBy(operName);
                this.insertRecKjInsideManagement(file);
                successNum++;
                successMsg.append("<br/>" + successNum + "、文件 " + file.getTitle() + " 导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、文件 " + file.getTitle() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            //手工回滚异常
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public File selectRecordFileExport(String archivesId) {

        List<RecKjInsideManagement> insideList = this.recKjInsideManagementListByParentId(archivesId);
        if (CollUtil.isNotEmpty(insideList)) {
            List<File> files = CollUtil.newArrayList();
            File f = null;
            String[] filepathArr = null;
            String[] imagespathArr = null;
            for (RecKjInsideManagement rm : insideList) {
                //文件存储路径
                String filePath = rm.getObjStr11();
                if (StrUtil.isNotEmpty(filePath)) {
                    filepathArr = filePath.split(",");
                    for (String s : filepathArr) {
                        filePath = RuoYiConfig.getProfile() + File.separator + s.replace("/profile", "");
                        f = new File(filePath);
                        files.add(f);
                        //   System.out.println(filePath);
                    }
                }
                //图片存储路径
                String imgpath = rm.getObjStr12();
                if (StrUtil.isNotEmpty(imgpath)) {
                    imagespathArr = imgpath.split(",");
                    for (String s : imagespathArr) {
                        filePath = RuoYiConfig.getProfile() + File.separator + s.replace("/profile", "");
                        f = new File(filePath);
                        files.add(f);
                    }
                }
            }
            List<Map<String, Object>> excellist = CollUtil.newArrayList();
            //表格
           /* File excelFile = HutoolExcelUtiles.RecordFileExport(JSONArray.parseArray(JSONObject.toJSONString(list)));
            files.add(excelFile);*/
            //生成zip
            String zipPath = RuoYiConfig.getZipPath() + archivesId + "_案卷包" + IdUtil.getSnowflake().nextIdStr() + ".zip";
            File[] zipfiles = ArrayUtil.toArray(files, File.class);

            File file = ZipUtil.zip(FileUtil.file(zipPath), false, zipfiles);
            //   System.out.println(fres.getAbsoluteFile());
            return file;
        }
        return null;
    }
}
